<?php

namespace App\Http\Controllers\Admin\Service;

use App\Exports\OfficeExport;
use App\Http\Controllers\Admin\Examine\Record;
use App\Http\Controllers\Controller;
use App\Http\Requests\service\AbnormalRequest;
use App\Models\administration\OfficeModel;
use App\Models\FlightModel;
use App\Models\OrderModel;
use App\Models\service\AbnormalConfigModel;
use App\Models\service\AbnormalModel;
use App\Models\service\CompensateModel;
use App\Models\service\ProblemModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class Abnormal extends Controller
{
    use AbnormalRequest;

    /**
     * Notes:列表
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request) {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        $order_sn = $request->input('order_sn', '');
        $sn = $request->input('sn', '');
        $destination = $request->input('destination', '');
//        $order_status = $request->input('order_status', '');
        $status = $request->input('status', '');
        $type = $request->input('type', '');
        $create_start = $request->input('create_start', '');
        $create_end = $request->input('create_end', '');

        $query = AbnormalModel::query()->with(['take_order', 'customer', 'order']);

        if($order_sn){
            $take_order_id = TakeOrderModel::where('sn', $order_sn)->value('id') ??  '';
            $query = $query->where('take_order_id', $take_order_id);
        }

        if($sn){
            $order_id = OrderModel::where('sn', $sn)->value('id') ??  '';
            $query = $query->where('order_id', $order_id);
        }

        if($destination){
            $query = $query->where('arrive_port_code', $destination);
        }

        if($status){
            $query = $query->where('status', $status);
        }

        if($type){
            $query = $query->where('type', $type);
        }

        if($create_start && $create_end){
            $query = $query->whereBetween('created_at', [$create_start, $create_end]);
        }

        $total = $query->count('id');
        $items = $query
            ->offset(($page-1) * $limit)
            ->limit($limit)
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'id' => $item->id,
                'customer_name' => $item->customer->name ?? '',
                'customer_sn' => $item->customer->sn ?? '',
                'take_order_sn' => $item->take_order->sn ?? '',
                'order_sn' => $item->order->sn ?? '',
                'des_country_name' => $item->take_order->destination ?? '',
                'type' => $item->type,
                'type_name' => AbnormalModel::TYPE[$item->type] ?? '',
                'abnormal_desc' => $item->abnormal_desc,
                'status' => $item->status,
                'status_text' => AbnormalModel::STATUS[$item->status] ??  '',
                'handle_mode' => AbnormalModel::DEAL_TYPE[$item->deal_type] ?? '',
                'remarks' => $item->remarks,
                'created_at' => $item->created_at->toDateTimeString()
            ];
            return $res;
        });

        return $this->success(['list' => $list, 'total' => $total]);
    }

    public function add(Request $request) {
        $params = $request->all();
        $check_res = self::admin_add_check($params);
        $order_sn = $request->input('order_sn', '');
        $take_order_sn = $request->input('take_order_sn', '');

        if($check_res->faild){
            return $this->error($check_res->err);
        }

        if(!$order_sn && !$take_order_sn){
            return $this->error('请填写入仓号或提单号');
        }

        $order_id = $take_order_id = $customer_id = 0;

        if($order_sn){
            $order_find = OrderModel::where('sn', $order_sn)->first();
            if(!$order_find){
                return $this->error('入仓号不存在');
            }
            $order_id = $order_find->id;
            $customer_id = $order_find->customer_id;
        }

        if($take_order_sn){
            $take_order_find = TakeOrderModel::where('sn', $take_order_sn)->first();
            if(!$take_order_find){
                return $this->error('提单号不存在');
            }
            $take_order_id = $take_order_find->id;
            $customer_id = $take_order_find->customer_id;
        }


//        $flight_find = FlightModel::find($find->flight_id);
//
//        if(!$flight_find){
//            return $this->error('没有航班信息');
//        }

        DB::beginTransaction();
        try {

            $model = new AbnormalModel();

            $model->order_id = $order_id;
            $model->take_order_id = $take_order_id;
            $model->customer_id = $customer_id;
            $model->type = $params['type'];
            $model->abnormal_desc = $params['abnormal_desc'];
            $model->source = 2;
            $model->save();

            if($order_sn && $order_find){
                $order_find->is_exception = 1;
                $order_find->save();
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }

        return $this->success();
    }

    /**
     * Notes:开始处理
     * User: xiangzi
     * Date: 2024/9/19
     * Time: 15:53
     * @return \Illuminate\Http\JsonResponse
     */
    public function start(Request $request, $id) {
        $model = AbnormalModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        if($model->status != 1){
            return $this->error('当前状态错误');
        }

        $model->status = 2;
        $model->start_time = date('Y-m-d H:i:s');
        $model->save();

        return $this->success();
    }

    /**
     * Notes:处理完成
     * User: xiangzi
     * Date: 2024/9/5
     * Time: 14:35
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::handle_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = AbnormalModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        if($model->status != 2){
            return $this->error('当前状态错误');
        }

        $model->deal_type = $params['mode_id'];
        $model->status = 3;
        $model->remarks = isset($params['remarks']) ? $params['remarks'] : '';
        $model->save();

        if($model->deal_type == 3){
            $take_order = TakeOrderModel::find($model->take_order_id);
            $flight = FlightModel::find($take_order->flight_id);

            $compensate = new CompensateModel();
            $compensate->customer_id = $model->customer_id;
            $compensate->order_id = $model->order_id;
            $compensate->take_order_id = $model->take_order_id;
            $compensate->created_admin_id = $auth->id;
            $compensate->flight_date = $flight ? date('Y-m-d', strtotime($flight->take_off_time)) : '';
            $compensate->start_port_code = $flight ? $flight->start_port_code : '';
            $compensate->arrive_port_code = $flight ? $flight->arrive_port_code : '';
            $compensate->status = 0;
            $compensate->source = 1;
            $compensate->save();
        }


        return $this->success();
    }

    /**
     * Notes:转问题件
     * User: xiangzi
     * Date: 2024/9/19
     * Time: 14:44
     * @return \Illuminate\Http\JsonResponse
     */
    public function problem(Request $request, $id){
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::problem_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = AbnormalModel::find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $order = OrderModel::find($model->order_id);
        if(!$order){
            return $this->error('入仓单不存在');
        }

        $find = ProblemModel::where('order_id', $order->id)->first();
        if($find){
            return $this->error('该入仓单已登记问题件');
        }

        DB::beginTransaction();
        try {
            $problem = new ProblemModel();
            $problem->order_id = $model->order_id;
            $problem->customer_id = $order->customer_id;
            $problem->number = $order->big_pkgs;
            $problem->weight = $order->storage_weight;
            $problem->type_id = $params['type_id'];
            $problem->description = $params['description'] ?? '';
            $problem->is_turn = 1;
            $problem->abnormal_id = $id;
            $problem->created_admin_id = $auth->id;
            $problem->save();

            $model->status = 4;
            $model->turn_time = date('Y-m-d H:i:s');
            $model->save();

            $order->is_issue = 1;
            $order->save();
            DB::commit();
        }catch (\Exception $e) {
            DB::rollBack();
            return $this->error($e->getMessage());
        }


        return $this->success();
    }

    /**
     * Notes:异常件转化设置
     * User: xiangzi
     * Date: 2024/9/19
     * Time: 15:25
     * @return \Illuminate\Http\JsonResponse
     */
    public function config(Request $request)
    {
        $auth = $request->get('auth');
        $params = $request->all();

        $check_res = self::day_check($params);
        if($check_res->faild){
            return $this->error($check_res->err);
        }

        $model = AbnormalConfigModel::find(1);
        if(!$model){
            $model = new AbnormalConfigModel();
        }

        $model->day = $params['day'];
        $model->created_admin_id = $auth->id;
        $model->save();

        return $this->success();
    }

    /**
     * Notes:详情
     * User: xiangzi
     * Date: 2024/9/26
     * Time: 16:00
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request)
    {
        $id = intval($request->input('id', 0));
        $model = AbnormalModel::with('mode')->find($id);
        if(!$model){
            return $this->error('数据不存在');
        }

        $return = [
            'base_Info' => [
                'abnormal_time' => $model->created_at->toDateTimeString(),
                'status_text' => AbnormalModel::STATUS[$model->status],
                'abnormal_desc' => $model->abnormal_desc,
                'handle_desc' => $model->handle_desc,
                'type_name' => AbnormalModel::TYPE[$model->type],
                'file' => json_decode($model->file, true),
            ]
        ];


        $return['handle_info'] = [];

        $return['handle_info'][] = [
            'time' => $model->created_at->toDateTimeString(),
            'desc' => '反馈异常',
        ];

        if($model->start_time){
            $return['handle_info'][] = [
                'time' => $model->start_time,
                'desc' => '开始处理'
            ];
        }

        if($model->end_time){
            $mode = $model->mode->name ?? '';
            $return['handle_info'][] = [
                'time' => $model->end_time,
                'desc' => '处理完成  ' . '处理方式：' . $mode . '，处理备注：' . $model->remarks,
            ];
        }

        if($model->turn_time) {
            $return['handle_info'][] = [
                'time' => $model->turn_time,
                'desc' => '转问题件'
            ];
        }

        return $this->success($return);
    }


    public function export(Request $request)
    {
        $ids = $request->input('ids', []);
        if(empty($ids)){
            return $this->error('请选择要导出的数据');
        }

        $query = AbnormalModel::query()->with('mode')->with('order' , function($query){
            $query->with('customer', 'des_country', 'take_order');
        });
        $query->whereIn('id', $ids);
        $items = $query
            ->orderBy('id', 'desc')
            ->get();

        $list = $items->map(function($item) {
            $res = [
                'customer_name' => $item->order->customer ? $item->order->customer->name : '',
                'order_sn' => $item->order ? $item->order->sn : '',
                'take_order_sn' => $item->order->take_order ? $item->order->take_order->sn : '',
                'des_country_name' => $item->order->airport->country_name ?? '' ?? '',
                'type_name' => AbnormalModel::TYPE[$item->type],
                'abnormal_desc' => $item->abnormal_desc,
                'status_text' => AbnormalModel::STATUS[$item->status],
                'handle_mode' => $item->mode ? $item->mode->name : '',
                'created_at' => $item->created_at->toDateTimeString()
            ];
            return $res;
        });

        $file_name = '异常列表-'.date('Ymd').'.xlsx';
        return Excel::download(new OfficeExport($list), $file_name);
    }

}
